import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { computed } from 'vue'
import { useUserStore } from './user'
import { addCartAPI, getCartListAPI, deleteCartAPI, mergeCartAPI } from '@/apis/cart'


export const useCartStore = defineStore('cart', () => {
  const cartList = ref([])

  // 获取购物车列表
  const getCartList = async () => {
    if(isLogin.value){
      const res = await getCartListAPI()
      cartList.value = res.result
    }
  }

  //合并购物车
  const mergeCart = async () => {
    if(isLogin.value){
      const arr = cartList.value.map(item => ({
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }))
      await mergeCartAPI(arr)
    }
  }

  // 加入购物车
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  const addCart = async (goods) => {
    if(isLogin.value){
      const {skuId,count} = goods
      addCartAPI({skuId,count})
      getCartList()
    }else{
      if(goods === null){ElMessage.error('请选择商品')}
    else{
      // 检查购物车是否已经存在该商品
    const item = cartList.value.find(item => goods.skuId === item.skuId)
    if (item) {
      // 如果存在，更新数量
      item.count += goods.count
    } else {
      // 如果不存在，直接加入购物车
      cartList.value.push(goods)
    }
      ElMessage.success('加入购物车成功')
    }
    }
  }

  //删除购物车商品
  const deleteCart = async (skuId) => {
    if(isLogin.value){
      deleteCartAPI([skuId])
      getCartList()
    }else{
       cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }


  //清空购物车
  const clearCart = () => {
    cartList.value = []
  }

  // 单选
  const singleCheck = (selected, skuId) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = selected
  }
  // 全选
  const isAll = computed(() => cartList.value.every(item => item.selected))
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }


  //计算属性：总数和总价，选择的商品
  const totalCount = computed(() => {
    return cartList.value.reduce((pre, cur) => pre + cur.count, 0)
  })
  const totalPrice = computed(() => {
    return cartList.value.reduce((pre, cur) => pre + cur.count * cur.price, 0)
  })


  //filter函数是JavaScript中的一个数组方法，它创建一个新数组，其中包含通过提供的测试函数的所有元素。
  // 这个方法不会改变原始数组，而是返回一个新数组，其中包含符合条件的元素。如果没有元素通过测试，它将返回一个空数组。
  //已选择商品的价格和数量
  const selectedGoodsPrice = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((pre, cur) => pre + cur.count * cur.price, 0)
  })
  //已选择商品的数量
  const selectedGoodsCount = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((pre, cur) => pre + cur.count, 0)
  })



  return {
    cartList,
    addCart,
    deleteCart,
    totalCount,
    totalPrice,
    singleCheck,
    isAll,
    allCheck,
    selectedGoodsCount,
    selectedGoodsPrice,
    getCartList,
    clearCart,
    mergeCart
  }
}, {
  persist: true
})
